package cloud.psn.kiko.mail.service;

import cloud.kiko.psn.pojo.common.baz.mail.Mail;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class EmailService {
    @Value("${spring.mail.username}")
    private String defaultFrom;

    @Resource
    private JavaMailSender javaMailSender;

    /**
     * 发送邮件
     * @param html 正文格式，true-HTML格式，false-普通文本
     */
    public void sendMail(Mail mail, boolean html) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, mail.getAttachmentPaths().length>0);
            if (mail.getFrom() != null && !mail.getFrom().isEmpty()) {
                helper.setFrom(mail.getFrom());
            } else {
                helper.setFrom(defaultFrom);
            }
            helper.setTo(mail.getTo());
            helper.setSubject(mail.getSubject());
            helper.setText(mail.getContent(), html);
            // 添加多个附件
            for (String attachmentPath : mail.getAttachmentPaths()) {
                FileSystemResource file = new FileSystemResource(new File(attachmentPath));
                helper.addAttachment(file.getFilename(), file);
            }
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

}
